package com.acme.faturamento.view.businessdelegate;

import java.util.Collection;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.acme.faturamento.model.businessdelegate.PersistenceManagerRemote;
import com.acme.faturamento.model.businessdelegate.PersistenceManager;

public class PersistenceManagerBD {
    private PersistenceManagerRemote manager;
    private Context contexto;

    public PersistenceManagerBD() {
        try {
            manager = (PersistenceManagerRemote) getContexto().lookup(PersistenceManager.RemoteJNDIName);
        } catch (NamingException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    private Context getContexto() throws NamingException {
        if (contexto == null) {
            Properties properties = new Properties();
            properties.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
            properties.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces");
            properties.put("java.naming.provider.url", "localhost:1099");

            contexto = new InitialContext(properties);
        }
        return contexto;
    }

    public void salvar(Object objeto) {
        manager.salvar(objeto);
    }

    public <T>void apagar(Class<T> classe, Long pk) {
        manager.apagar(classe,pk);
    }

    public void atualizar(Object objeto) {
        manager.atualizar(objeto);
    }

    public void mesclar(Object objeto) {
        manager.mesclar(objeto);
    }

    public <T> T get(Class<T> entidadeClass, Object chavePrimaria) {
        return manager.get(entidadeClass, chavePrimaria);
    }
    public <T> Collection<T> getLista(String nomeQuery){
        return manager.getLista(nomeQuery);
    }
}
